package com.tuanbiao.presenter;

import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;

import com.hzjq.core.bean.CapEntity;
import com.hzjq.core.bean.ErrorCapEntity;
import com.hzjq.core.util.ErrorChecker;
import com.hzjq.lib.BlastKool;
import com.hzjq.lib.callback.NettedCallback;
import com.hzjq.lib.cap.auth.OnAuthCapCallback;
import com.hzjq.lib.cap.bean.CommResult;
import com.hzjq.lib.cap.bean.ErrorCap;
import com.hzjq.lib.cap.netted.NettedStatus;
import com.hzjq.lib.checker.CheckError;
import com.tuanbiao.base.mvp.BasePresenter;
import com.tuanbiao.constants.Constants;
import com.tuanbiao.controllers.BlastController;
import com.tuanbiao.data.callback.OnBaseResultCallback;
import com.tuanbiao.keyevent.KeyEventHelper;
import com.tuanbiao.utils.LibCollections;

import java.util.ArrayList;
import java.util.List;

import timber.log.Timber;

/**
 * @author abiao
 * @since 2022/4/26 9:32
 */
public class BlastNettedPresenter extends BasePresenter<BlastController.Model, BlastController.CheckView> implements BlastController.CheckPresenter {
    private boolean canCharge;
    private boolean isNetting;
    private List<ErrorCap> mErrorCaps;
    private List<ErrorCap> mDuplicateCaps;
    private List<ErrorCap> mMissCaps;
    private String errorMsg = "组网异常";
    private boolean safeLockIsOpen;
    private NettedStatus status;

    public BlastNettedPresenter(BlastController.Model model, BlastController.CheckView rootView) {
        super(model, rootView);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void init() {
        startCheck();
    }

    @Override
    public void checkNetted() {
        mRootView.showCheckDialog();
        mModel.checkNetted(error -> {
            mRootView.hideCheckDialog();
            if (error.getErrorCode() == CheckError.CHECK_SUCCESS) {
                startCheck();
            } else {
                mRootView.showMessage(error.getErrorMsg());
            }
        });

    }

    private void startCheck() {
        Timber.i("startCheck");
        canCharge = false;
        mRootView.setChargeEnable(false);
        mRootView.setCancelEnable(true);
        mRootView.setRecheckEnable(false);
        mRootView.showCheckResult(false, KeyEventHelper.getInstance().getNettedNoteSuccess());
        isNetting = true;
        mErrorCaps = null;
        mDuplicateCaps = null;
        mMissCaps = null;
        mModel.netted(new NettedCallback() {
            @Override
            public void notifyLockStateChanged(int i) {
                Timber.i("notifyLockStateChanged:" + i);
                //0关
                //1开
                safeLockIsOpen = i == 1;
            }

            @Override
            public void notifyVoltageElectricChanged(float v, float v1) {
                mRootView.showVoltageElectric(v, v1);
                Timber.i("notifyVoltageElectricChanged#v:" + v + ",v1:" + v1);
            }

            @Override
            public void notifyProgressChanged(@NonNull NettedStatus nettedStatus, int i, @NonNull String s) {
                mRootView.showProgress(i, s);
                mRootView.showCheckNote(s);
                status = nettedStatus;
                showNettStatus(nettedStatus);
                Timber.i("notifyProgressChanged#nettedStatus:" + nettedStatus + ",i:" + i + ",s:" + s);
            }

            @Override
            public void onResult(CommResult commResult) {
                mOnAuthCapCallback.onResult(commResult);
            }

            @Override
            public void onFailed(@NonNull String s) {
                mOnAuthCapCallback.onFailed(s);
            }
        });
    }


    private void showNettStatus(NettedStatus nettedStatus){
        Timber.e("nettedStatus = "+nettedStatus);
        switch (nettedStatus) {
            //雷管检查
            case CAP_CHECK:
                mRootView.showCheckStatus(Constants.NettedStatusName.CAP_CHECK);
                break;
            //下传发方案
            case CAP_UNDER:
                mRootView.showCheckStatus(Constants.NettedStatusName.CAP_UNDER);
                break;
            //授权检查
            case CAP_AUTH_CHECK:
                mRootView.showCheckStatus(Constants.NettedStatusName.CAP_AUTH_CHECK);
                break;
            //延时检查
            case CAP_TIME_CHECK:
                mRootView.showCheckStatus(Constants.NettedStatusName.CAP_TIME_CHECK);
                break;
            //方案检查
            case CAP_UNDER_CHECK:
                mRootView.showCheckStatus(Constants.NettedStatusName.CAP_UNDER_CHECK);
                break;
            default:
                break;
        }

    }

    @Override
    public void cancelNetted() {
        mRootView.setRecheckEnable(true);
        mRootView.setCancelEnable(false);
        mModel.cancelNetted();
    }

    @Override
    public void exitNetted() {
        mRootView.showExit();
        BlastKool.Companion.loader().authTimer().cancel();
        BlastKool.Companion.loader().delayTimer().cancel();
        mModel.exitNetted(new OnBaseResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                if (aBoolean) {
                    mRootView.killMyself();
                } else {
                    mRootView.exitFailed();
                    mRootView.showMessage("退出失败，请重试！");
                }
            }

            @Override
            public void onFinish() {
                mRootView.hideExit();
            }
        });
    }

    @Override
    public void startCharge() {
        if (!safeLockIsOpen) {
            mRootView.showMessage("安全锁未打开请打开安全锁再进行充电！");
            return;
        }
        if (canCharge) {
            mModel.cancelNetted();
            mRootView.startCharge();
        } else {
//            mRootView.showMessage("正在检测中...");
        }
    }


    private OnAuthCapCallback mOnAuthCapCallback = new OnAuthCapCallback() {

        @Override
        public void onSafeLockChanged(int i) {
            Timber.i("notifyLockStateChanged:" + i);
            safeLockIsOpen = i == 1;
        }

        @Override
        public void onAuthStatusChanged(@NonNull NettedStatus nettedStatus) {
            status = nettedStatus;
            showNettStatus(nettedStatus);
        }

        @Override
        public void onVoltageElectricChanged(float v, float v1) {
            mRootView.showVoltageElectric(v, v1);
        }

        @Override
        public void onProgressChanged(@NonNull String s, int i, int i1) {
            Timber.i("notifyProgressChanged#nettedStatus:" + ",i:" + i1 + ",s:" + s);
            mRootView.showProgress(i, s);
            mRootView.showCheckNote(s);
        }

        @Override
        public void onResult(CommResult commResult) {
            mRootView.setChargeEnable(commResult.isSuccess());
            mRootView.setCancelEnable(false);
            canCharge = commResult.isSuccess();
            isNetting = false;
            mRootView.setRecheckEnable(!commResult.isSuccess());
            errorMsg = "";
            if (commResult.isSuccess()) {
                mRootView.showCheckStatus("校验成功");
                mRootView.showCheckResult(true, KeyEventHelper.getInstance().getNettedNoteSuccess());
            } else {
                mErrorCaps = commResult.getFailedCaps();
                mDuplicateCaps = commResult.getMeetErrorCaps();
                mMissCaps = commResult.getMissErrorCaps();
                mRootView.showCheckStatus("校验失败");
                String msg = createErrorMsg(mErrorCaps, mDuplicateCaps, mMissCaps)+ KeyEventHelper.getInstance().getNettedNoteFailed();
                //if(!isContainAuthError()){
                    mRootView.showCheckResult(true,msg);
//                } else {
//                    mRootView.showCheckErrorResult("有"+mErrorCaps.size()+"发授权异常，有可能造成拒爆"+ KeyEventHelper.getInstance().getNettedNoteFailed());
//                }
            }
            Timber.i("onResult:" + commResult.isSuccess());
        }

        @Override
        public void onFailed(@NonNull String s) {
            isNetting = false;
            errorMsg = s;
            Timber.i("onFailed:" + s);
            mRootView.showCheckStatus("校验失败");
            mRootView.showCheckResult(true, s);
            mRootView.setChargeEnable(false);
            mRootView.setRecheckEnable(true);
            mRootView.setCancelEnable(false);
        }
    };

    private boolean isContainAuthError(){
        if(mErrorCaps.isEmpty()){
            return false;
        }
        int authErrorCount = 0;
        for (int i = 0; i < mErrorCaps.size(); i++) {
            CapEntity cap = mErrorCaps.get(i).getCap().getCap();
            ErrorCapEntity cap1 = ErrorChecker.Companion.checkContainAuth(cap);
            if(cap1 != null){
                authErrorCount ++;
                BlastKool.Companion.addBlastLog("组网E "+cap.getConvertUid());
            }
        }
        return authErrorCount == mErrorCaps.size();
    }

    @Override
    public void doErrorNext() {
        if(status != null){
            if (status == NettedStatus.CAP_UNDER_CHECK) {
                BlastKool.Companion.loader().authTimer().authTimer(mOnAuthCapCallback);
                mRootView.showCheckStatus("验证授权");
                mRootView.showCheckNote("正在验证授权");
                mRootView.showCheckResult(false,"正在验证授权");
            } else if (status == NettedStatus.CAP_AUTH_CHECK) {
                BlastKool.Companion.loader().delayTimer().checkTimer(mOnAuthCapCallback);
                mRootView.showCheckStatus("校时验证");
                mRootView.showCheckNote("正在校时");
                mRootView.showCheckResult(false,"正在校时");
            } else if (status == NettedStatus.CAP_TIME_CHECK) {
                canCharge = true;
                startCharge();
            }
        }
    }

    @Override
    public void checkErrorCaps() {
        if (isNetting) {
//            mRootView.showMessage("正在检测中...");
            return;
        }
        if (!LibCollections.isEmpty(mErrorCaps) || !LibCollections.isEmpty(mDuplicateCaps) || !LibCollections.isEmpty(mMissCaps)) {
            List<ErrorCap> errorCaps = new ArrayList<>();
            if (null != mErrorCaps) errorCaps.addAll(mErrorCaps);
            if (null != mDuplicateCaps) errorCaps.addAll(mDuplicateCaps);
            if (null != mMissCaps) errorCaps.addAll(mMissCaps);
            mRootView.startErrorCaps(errorCaps);
        } else {
            mRootView.showMessage(errorMsg);
        }
    }

    private String createErrorMsg(List<ErrorCap> errorCaps, List<ErrorCap> duplicateCaps, List<ErrorCap> missCaps) {
        if (LibCollections.isEmpty(duplicateCaps) && LibCollections.isEmpty(missCaps)
                && LibCollections.isEmpty(errorCaps)) {
            return "组网失败";
        }
        String errorMsg = "";
        if (!LibCollections.isEmpty(duplicateCaps)) {
            errorMsg = "有" + LibCollections.size(duplicateCaps) + "发雷管多接";
        }
        if (!LibCollections.isEmpty(missCaps)) {
            if (TextUtils.isEmpty(errorMsg)) {
                errorMsg = "有" + LibCollections.size(missCaps) + "发雷管漏接";
            } else {
                errorMsg += "和" + LibCollections.size(missCaps) + "发雷管漏接";
            }
        }
        if (!LibCollections.isEmpty(errorCaps)) {
            if (TextUtils.isEmpty(errorMsg)) {
                errorMsg = "有" + LibCollections.size(errorCaps) + "发雷管其他错误";
            } else {
                errorMsg += "和" + LibCollections.size(errorCaps) + "发雷管其他错误";
            }
        }
        return errorMsg;
    }
}